package com.wgq.uitest.exp6;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpServer implements Runnable{
    private final static int localPort = 5000;
    byte[] buf = new byte[1024];
    Handler handler;
    DatagramSocket localDs = null;
    public UdpServer(Handler handler) {
        this.handler = handler;
        try{
            localDs = new DatagramSocket(localPort);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(true){
            try{
                DatagramPacket localDp = new DatagramPacket(buf, 1024);
                localDs.receive(localDp);
                String rec = new String(localDp.getData(), localDp.getOffset(), localDp.getLength());
                Message msg = new Message();
                msg.what = 0x1234;
                Bundle bundle = new Bundle();
                bundle.putString("content", rec);
                msg.setData(bundle);
                handler.sendMessage(msg);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
